import router from "@/router"
import { useMainStore } from "@/stores/main"
import axios, { AxiosRequestConfig } from "axios"
import { ElMessage, ElMessageBox } from "element-plus"
// import { storeToRefs } from "pinia"

// const main = useMainStore()
// const { user } = storeToRefs(main)

let isRefresh = false
const request = axios.create({
  // baseURL: import.meta.env.VITE_API_BASEURL
})

// Add a request interceptor
request.interceptors.request.use(function (config) {
  // Do something before request is sent
  // 统一设置用户身份 token
  const main = useMainStore()
  if (main.user?.token) {
    config.headers!.Authorization = `Bearer ${main.user.token}`
  }
  return config
}, function (error) {
  // Do something with request error
  return Promise.reject(error)
})

// Add a response interceptor
request.interceptors.response.use(function (response) {
  // Any status code that lie within the range of 2xx cause this function to trigger
  // Do something with response data
  // 统一处理响应错误
  const status = response.data.status
  // 请求正常
  if (!status || status === 200) {
    return response
  }
  // token 过期
  if (status === 410000) {
    if (isRefresh) return Promise.reject(response.data)
    isRefresh = true
    ElMessageBox.confirm('登录已过期， 是否跳转到登录页面？', '登录过期', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    }).then(() => {
      // 清除本地过期登录状态
      const main = useMainStore()
      main.setUser(null)
      // 跳转到登录页
      router.push({
        name: 'login',
        query: {
          redirect: router.currentRoute.value.fullPath
        }
      })
    }).finally(() => {
      isRefresh = false
    })
    return Promise.reject(response.data)
  }
  // others error
  ElMessage.error(response.data.msg || '请求出错，请稍后重试')
  return Promise.reject(response.data)
  // if (response.data.status && response.data.status !== 200) {
  //   ElMessage.error(response.data.msg || '请求出错，请稍后重试')
  //   return Promise.reject(response.data)
  // }
  // return response
}, function (error) {
  // Any status codes that falls outside the range of 2xx cause this function to trigger
  // Do something with response error
  return Promise.reject(error)
})

export default <T = any>(config: AxiosRequestConfig) => {
  return request(config).then(res => {
    return (res.data.data || res.data) as T
  })
}

// export default request
